package cn.south.campus.common.file.service;

import cn.south.campus.common.config.FileUploadConfig;
import cn.south.campus.common.exceptions.BusinessException;
import cn.south.campus.common.file.vo.FileVO;
import cn.south.campus.common.model.enums.CommonEnums;
import cn.south.campus.common.utils.AssertUtils;
import cn.south.campus.common.utils.FileUtils;
import cn.south.campus.common.utils.GenSerializeUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *
 * </p>
 *
 * @author chow
 * @since 2023/3/21 19:54
 */
public abstract class AbstractFileUploadService {


    public FileVO fileUpload(MultipartFile file, String fileName) {
        //校验文件大小
        long size = file.getSize();
        AssertUtils.isLtE(size, FileUploadConfig.MAX_SIZE, CommonEnums.FILE_OUT_OF_SIZE_ERROR);

        //校验文件拓展名
        String extension = "";
        if (StringUtils.hasText(fileName)) {
            extension = fileName.substring(fileName.lastIndexOf(".") + 1);
        } else {
            //校验文件名
            String originalFilename = file.getOriginalFilename();
            AssertUtils.isNotBlank(originalFilename, CommonEnums.FILE_NAME_BLANK_ERROR);
            extension = FileUtils.getExtension(originalFilename, file.getContentType());
        }
        AssertUtils.isNotNull(extension, CommonEnums.FILE_TYPE_ERROR);
        if (!FileUploadConfig.ALLOW_FILE_TYPE.contains(extension)) {
            throw new BusinessException(CommonEnums.FILE_TYPE_ERROR);
        }
        //生成文件名
        FileVO fileBO = new FileVO();
        fileBO.setFileName(getFileName(extension));
        fileBO.setOriginalName(fileName);
        uploadFile(fileBO, file);
        return fileBO;
    }

    protected abstract void uploadFile(FileVO fileVO, MultipartFile file);

    @SuppressWarnings("all")
    private String getFileName(String extension) {
        return GenSerializeUtil.genFileName() + "." + extension;
    }
}
